package DataCenter;

import java.io.*;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.MapMessage;

import DataBasic.*;
import Log.HostInfoModifier;

public class HostModifier extends MetaHost implements Modifer,HostInfoModifier{

	private static HostModifier instance;
	
	private HostAccessor hostAccessor;
	private List<String> states;
	private List<String> ports;
	private List<String> names;
	private List<String> ips;
	private List<String> uses;

	private InputStream inputStream;
	
	public synchronized static HostModifier sharedInstance() {
		if (instance == null)
			instance = new HostModifier();
		
		return instance;
	}

	private HostModifier() {
		super();
		hostAccessor = HostAccessor.sharedInstance();
		
		names = hostAccessor.getHostNames();
		ips = hostAccessor.getHostIps();
		ports = hostAccessor.getHostPorts();
		states = hostAccessor.getHostStates();
		uses = hostAccessor.getHostUses();
	}

	@Override
	public void beginUpdate() {
		// modify the file in classpath (memory)
		try {
			inputStream = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME);
			this.prop.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void endUpdate() {
		try {
			FileOutputStream outStream = new FileOutputStream(FILE_PATH);
			prop.store(outStream, " ");
			outStream.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void updateHostInfo(MapMessage infos) {
		beginUpdate();
		
		try {
			String name = infos.getString("Name");
			int index = names.indexOf(name);
			ips.set(index, infos.getString("Ip"));
			ports.set(index, infos.getString("Port"));
			states.set(index, infos.getString("State"));
			uses.set(index, "No");
			
			String[] keyList ={"Name", "Ip", "Port", "State"};
			
			for (String key : keyList) {
				String keyInProp = key + String.valueOf(index+1);
				prop.setProperty(keyInProp, infos.getString(key));
				System.out.println(keyInProp + " " + infos.getString(key));
			}
			
			prop.setProperty("Using"+String.valueOf(index), "No");
			
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
		endUpdate();
	}
	
	public void updateHostUsing(String hostName) {
		this.beginUpdate();
		
		int index = names.indexOf(hostName);
		if (hostAccessor.isTheHostUnusing(hostName)) {
			uses.set(index, "Yes");
			String key = "Using" + String.valueOf(index+1);
			prop.setProperty(key, "Yes");
		}
		else {
			uses.set(index, "No");
			String key = "Using" + String.valueOf(index+1);
			prop.setProperty(key, "No");
		}
		
		this.endUpdate();
	}
	
}
